import {
  IGetModelGetRes,
  IPostDataCfgExecuteReq,
  IPostDataCfgExecuteRes,
  postDataCfgExecute,
  postDataCfgGet,
  postDataCfgPage
} from '@/api';
import { MciButton, MciDialog, MciEmpty, MciRadioGroup, MciSelect, MciSubCard, MciTableColumn } from '@/components/base';
import { FormMode } from '@/components/base/Form/mode';
import { IOption } from '@/components/base/Select';
import { FieldsDataTable } from '@/components/business/FieldsDataTable';
import { useCurrentNode } from '@/hooks/useCurrentNode';
// import { useDictStore } from '@/store/dict';
import { TVariables } from '@/utils/graph';
import { DATA_LOAD_TYPE } from '../DataSet/data';
import { DataSet } from '../DataSet';
import { IDataLoadForm } from '../DataSet/type';
import { IDataLoad } from '../../type';
import TestReq from '@/views/data-source/components/DataModel/components/TestReq/index.vue';
import TestRes from '@/views/data-source/components/DataModel/components/TestRes/index.vue';
import { useFlow } from '@/hooks/useFlow';

export const ModelConfig = defineComponent({
  name: 'ModelConfig',
  setup() {
    // const dictStore = useDictStore();
    const currentNode = useCurrentNode();
    const { flowState } = useFlow();
    // 节点变量
    const variablesWithSystem = computed<any[]>(() => {
      // const systemVars = dictStore.systemVars || [];
      const currentAndParentPrivateVariables = currentNode.currentAndParentPrivateVariables.value || [];
      return currentAndParentPrivateVariables;
    });

    // 读数据
    const oldData = currentNode.getDataLoad();
    // 方式
    const cfgType = ref(DATA_LOAD_TYPE.EDIT);

    const dataLoadForm = reactive<IDataLoadForm>({
      tableName: '',
      columns: [],
      conditions: {
        conditions: [],
        conjs: [],
        splitIndexes: []
      }
    });

    // if (oldData) {
    cfgType.value = oldData?.cfgType || DATA_LOAD_TYPE.CHOOSE;
    const dataSet = oldData?.dataSet;
    dataLoadForm.tableName = dataSet?.tableName || '';
    dataLoadForm.columns = dataSet?.columns || [];
    dataLoadForm.conditions = dataSet?.conditions || {
      conditions: [],
      conjs: [],
      splitIndexes: []
    };
    // }

    // 编辑数据集
    let isVisible = ref(false);
    const exeAddRef = ref();
    const confirmHandle = () => {
      exeAddRef.value?.formValidate();
    };

    // 测试数据集设置
    let isTestVisible = ref(false);
    // 执行参数
    // const parametersAddRe
    const testReqData = ref<any[]>([]);
    const testReqResult = ref<any[]>([]);
    // 执行返回
    const tesResTableData = ref<any[]>([]);
    const tesResTableColumn = ref<any[]>([]);

    const handleTestReqChange = (value: any) => {
      testReqResult.value = value;
    };

    // 执行请求
    const exeRequest = async () => {
      const paramsObj: any = {};
      if (testReqResult.value) {
        for (const iterator of testReqResult.value) {
          if (iterator) {
            paramsObj[iterator.varName] = iterator.value ? iterator.value : iterator.initValue;
          }
        }
      }

      const params: IPostDataCfgExecuteReq = {
        tableName: dataLoadForm.tableName,
        columns: dataLoadForm.columns,
        variables: [], // variablesWithSystem.value,
        conditions: dataLoadForm.conditions,
        params: paramsObj
      };

      const data: IPostDataCfgExecuteRes = await postDataCfgExecute(params);
      // 执行
      tesResTableData.value = [];
      tesResTableColumn.value = [];
      if (data) {
        const { results, variables } = data;
        if (results) tesResTableData.value = results;
        if (variables) {
          tesResTableColumn.value = variables.map((item: any) => {
            return {
              prop: item.varName,
              label: item.varLabel ? item.varLabel : item.varName
            };
          });
        }
      }
    };

    const value = ref<string>('');
    const options = ref<IOption[]>([]);
    const currNodeVariablesReq = ref<TVariables[]>([]);
    const currNodeVariablesRes = ref<TVariables[]>([]);

    const loading = ref(false);

    const getModelResponse = async (id: string) => {
      if (!id) return;
      let variables: IGetModelGetRes['variables'] = [];
      loading.value = true;
      const res = await postDataCfgGet({ id });
      variables = res.variables || [];
      loading.value = false;
      currNodeVariablesReq.value = variables?.filter((item) => item.scope === 'REQUEST') || [];
      currNodeVariablesRes.value = variables?.filter((item) => item.scope === 'RESPONSE') || [];
      currentNode.saveCurrentPrivateNodeVariables(variables);
    };

    const clearForm = () => {
      dataLoadForm.tableName = '';
      dataLoadForm.columns = [];
      dataLoadForm.conditions = {
        conditions: [],
        conjs: [],
        splitIndexes: []
      };
      const data: IDataLoad = {
        cfgType: DATA_LOAD_TYPE.EDIT,
        dataSet: dataLoadForm
      };
      currentNode.saveDataLoad(data);
    };
    const clearParams = () => {
      currNodeVariablesRes.value = [];
      currNodeVariablesRes.value = [];
      currNodeVariablesReq.value = [];
    };

    onMounted(async () => {
      const data = currentNode.getNodeData();
      const { list = [] } = await postDataCfgPage({ pageNo: 1, pageSize: 100 });

      const dataOptions = list.map((item: any) => {
        return {
          value: item.id,
          label: item.cfgName
        };
      });

      if (data?.actionId) {
        value.value = data.actionId;
        cfgType.value === DATA_LOAD_TYPE.CHOOSE && getModelResponse(data.actionId);
      }

      options.value = dataOptions;
    });

    return () => {
      return (
        <MciSubCard title="加载设置">
          <div class="flex justify-between bg-fill-2 py-4 px-8">
            <MciRadioGroup
              disabled={flowState.value === 'view'}
              modelValue={cfgType.value}
              direction={'row'}
              options={[
                {
                  text: '新增私有数据集',
                  label: DATA_LOAD_TYPE.EDIT
                },
                {
                  text: '引入公共数据集',
                  label: DATA_LOAD_TYPE.CHOOSE
                }
              ]}
              onChange={(val: number) => {
                cfgType.value = val;
                switch (val) {
                  case DATA_LOAD_TYPE.CHOOSE:
                    value.value && getModelResponse(value.value);
                    break;
                  case DATA_LOAD_TYPE.EDIT:
                    const data: IDataLoad = {
                      cfgType: cfgType.value,
                      dataSet: dataLoadForm
                    };
                    currentNode.saveDataLoad(data);
                    break;
                  default:
                    break;
                }
              }}
            />

            {flowState.value === 'edit' && cfgType.value === DATA_LOAD_TYPE.EDIT && (
              <div class="py-4">
                <MciButton
                  type="primary"
                  icon={'mci-icon-edit-1'}
                  link
                  onClick={() => {
                    isVisible.value = true;
                  }}>
                  修改
                </MciButton>
                <MciButton
                  type="primary"
                  link
                  icon="mci-icon-check"
                  onClick={() => {
                    testReqData.value = variablesWithSystem.value;
                    isTestVisible.value = true;
                  }}>
                  测试
                </MciButton>
                <MciButton
                  type="primary"
                  link
                  icon="mci-icon-delete"
                  onClick={() => {
                    clearForm();
                  }}>
                  删除
                </MciButton>
              </div>
            )}
          </div>
          {cfgType.value === DATA_LOAD_TYPE.EDIT ? (
            <div class="mt-8 mx-8">
              <FormMode mode="view">
                <DataSet dataSetData={dataLoadForm} />
              </FormMode>
              {isVisible.value && (
                <MciDialog
                  title={'数据集设置'}
                  modelValue={true}
                  width={1000}
                  draggable={true}
                  customClass="max-height-dialog"
                  onClose={() => {
                    isVisible.value = false;
                  }}>
                  {{
                    default() {
                      return (
                        <div class="flex">
                          <DataSet
                            dataSetData={dataLoadForm}
                            ref={exeAddRef}
                            onValid={(val: IDataLoadForm) => {
                              isVisible.value = false;
                              dataLoadForm.tableName = val.tableName;
                              dataLoadForm.columns = val.columns;
                              dataLoadForm.conditions = val.conditions;
                              const data: IDataLoad = {
                                cfgType: cfgType.value,
                                dataSet: dataLoadForm
                              };
                              currentNode.saveDataLoad(data);
                            }}
                          />
                        </div>
                      );
                    },
                    footer() {
                      return (
                        <>
                          <MciButton
                            onClick={() => {
                              isVisible.value = false;
                            }}>
                            取消
                          </MciButton>
                          <MciButton type="primary" onClick={confirmHandle}>
                            确定
                          </MciButton>
                        </>
                      );
                    }
                  }}
                </MciDialog>
              )}
              {isTestVisible.value && (
                <MciDialog
                  title={'数据集测试'}
                  modelValue={true}
                  width={1000}
                  draggable={true}
                  customClass="max-height-dialog"
                  onClose={() => {
                    isTestVisible.value = false;
                  }}>
                  {{
                    default() {
                      return (
                        <div class="flex flex-col">
                          <TestReq data={testReqData.value} onChange={handleTestReqChange} />
                          <div class="mt-16">
                            <TestRes table-data={tesResTableData.value} table-column={tesResTableColumn.value} />
                          </div>
                        </div>
                      );
                    },
                    footer() {
                      return (
                        <>
                          <MciButton
                            onClick={() => {
                              isTestVisible.value = false;
                            }}>
                            关闭
                          </MciButton>
                          <MciButton type="primary" onClick={exeRequest}>
                            测试
                          </MciButton>
                        </>
                      );
                    }
                  }}
                </MciDialog>
              )}
            </div>
          ) : (
            <div class="mt-8">
              <MciSelect
                class="w-full"
                filterable
                clearable
                modelValue={value.value}
                list={options.value}
                onChange={(val) => {
                  value.value = val;
                  currentNode.setData({
                    actionId: val
                  });
                  if (!val) {
                    clearParams();
                  } else {
                    getModelResponse(val);
                    currentNode.saveDataLoad({
                      cfgType: cfgType.value
                    });
                  }
                }}
              />
              {currNodeVariablesReq.value.length > 0 && (
                <div class="py-16">
                  {<div class="text-value-14_bold mt-12">入参</div>}
                  <FieldsDataTable data={currNodeVariablesReq.value}>
                    <MciTableColumn label="默认值" prop="initValue" />
                  </FieldsDataTable>
                </div>
              )}
              {currNodeVariablesRes.value.length > 0 && (
                <div class="mb-20 py-16">
                  <div class="text-value-14_bold">模型返回字段</div>
                  <FieldsDataTable data={currNodeVariablesRes.value} />
                </div>
              )}
              {currNodeVariablesReq.value.length <= 0 && currNodeVariablesRes.value.length <= 0 && (
                <div class="custom-empty my-24">
                  <MciEmpty tipText={'暂无数据'} />
                </div>
              )}
            </div>
          )}
        </MciSubCard>
      );
    };
  }
});
